package org.zxp.thread.communication.piped;

import java.io.*;

/**
 * @program: zxp-thread-test
 * @description: 主线程与R_Thread线程通讯  主线程把信息输入pipedOutputStream，pipedOutputStream与pipedInputStream连
 * R_Thread通过pipedInputStream接收
 * 当无消息时阻塞在pipedInputStream.read方法上，除非主线程close pipedOutputStreamting后R_Thread read方法==-1 退出，主线程也退出
 * @author: X-Pacific zhang
 * @create: 2019-05-18 17:08
 **/
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        pipedOutputStream.connect(pipedInputStream);
        new Thread(new R_Thread(pipedInputStream)).start();
//        for (int i = 0; i < 10; i++) {
//            pipedOutputStream.write((i+"我来也").getBytes());
//        }
//        Thread.sleep(1000);
//        pipedOutputStream.write(("第二波").getBytes());
//        pipedOutputStream.close();
//        br.close();
        //读 输入BYE结束
        while(true){
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String msg = br.readLine();
            pipedOutputStream.write(msg.getBytes());
            if(msg.equals("bye")){
                pipedOutputStream.close();
                br.close();
                return;
            }
        }
    }
}
